package com.aispeech.lyra.nativec.opensles;


import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.stream.Stream;

/**
 * 保存录音数据
 */
public enum AudioDataSaver {

    instance;

    private String TAG = "AudioDataSaver";
    public String pcmFolder = "/sdcard/etc/pcm/";//音频保存目录
    private FileOutputStream mOriginalPcmFileWriter;
    public String fullName = null;
    private File fullNameFile = null;
    private volatile boolean isAllowSaving = true;
    public String inputname="";

    public boolean isAllowSaving() {
        return isAllowSaving;
    }

    public void setAllowSaving(boolean allowSaving) {
        isAllowSaving = allowSaving;
    }

    public File getFullNameFile() {
        return fullNameFile;
    }

    /**
     * 保存本地pcm数据， /sdcard/etc/pcm/日期.pcm
     */
    public synchronized void savePcmDatatoLocal(byte[] pcmdata) {
        if (!isAllowSaving) {
            Log.e(TAG, "not  AllowSave data");
            return;
        }
        try {
            if (fullNameFile == null || (!fullNameFile.exists())) {
                Date d = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-HH_mm_ss");
                fullName = pcmFolder + sdf.format(d) + inputname+".pcm";
                fullNameFile = new File(fullName);
                if (!fullNameFile.getParentFile().exists()) {
                    fullNameFile.getParentFile().mkdirs(); // 父目录不存在，就创建一个
                }
                Log.w(TAG, "fullNameFile:" + fullNameFile);
            }

            if (mOriginalPcmFileWriter == null) {
                mOriginalPcmFileWriter = new FileOutputStream(fullNameFile);
                Log.w(TAG, "new FileOutputStream,fullName:" + fullName);
            }
            mOriginalPcmFileWriter.write(pcmdata);

        } catch (Exception ex) {
            Log.w(TAG, "Exception:" + ex.getLocalizedMessage());
            ex.printStackTrace();
        }



    }


    public synchronized void stopSave() {
        Log.w(TAG, "stopSave  called, fullNameFile =null");
        if (mOriginalPcmFileWriter != null) {
            try {
                mOriginalPcmFileWriter.flush();
                mOriginalPcmFileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mOriginalPcmFileWriter = null;
        }
        if (fullNameFile != null) {
            fullNameFile = null;
        }
    }


}
